package com.changgou.service.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.common.util.IdWorker;
import com.changgou.goods.pojo.*;
import com.changgou.service.goods.dao.BrandMapper;
import com.changgou.service.goods.dao.CategoryMapper;
import com.changgou.service.goods.dao.SkuMapper;
import com.changgou.service.goods.dao.SpuMapper;
import com.changgou.service.goods.service.SpuService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.netflix.discovery.converters.Auto;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    /**
     * 查询所有商品的spu信息
     *
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }


    /**
     * 根据id查询商品
     *
     * @param id
     * @return
     */
    @Override
    public Goods findGoodsById(String id) {
        //根据id查询到spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        Goods goods = new Goods();
        //将spu信息封装到goods中
        goods.setSpu(spu);

        //查询sku的集合信息
        Example example = new Example(Sku.class);

        Example.Criteria criteria = example.createCriteria();

        //根据spu进行sku列表查询
        criteria.andEqualTo("spuId",id);
        //查询所有的sku集合
        List<Sku> skuList = skuMapper.selectByExample(example);

        goods.setSkuList(skuList);
        return goods;
    }

    @Override
    @Transactional
    public void add(Goods goods) {
        //1.获取到需要添加spu
        Spu spu = goods.getSpu();

        //设置分布式id
        long spuId = idWorker.nextId();
        spu.setId(String.valueOf(spuId));

        //设置删除状态
        spu.setIsDelete("0");
        //设置上架状态
        spu.setIsMarketable("0");
        //设置审核状态
        spu.setStatus("0");

        //添加到数据库中
        spuMapper.insertSelective(spu);

        saveSkuList(goods);

    }

    //添加sku数据
    private void saveSkuList(Goods goods) {
        //获取sku集合数据
        List<Sku> skuList = goods.getSkuList();

        Spu spu = goods.getSpu();
        //获取商品分类
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());

        //获取商品的品牌
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());


        if (skuList != null) {
        //遍历sku集合  循环填充数据到sku中
            for (Sku sku : skuList) {
                //设置skuid
                sku.setId(String.valueOf(idWorker.nextId()));
                //设置sku规格数据
                if (StringUtils.isEmpty(sku.getSpec())) {
                    sku.setSpec("{}");
                }
                //设置sku规格名称(spu名称+规格)
                String name =spu.getName();

                //将规格json转换为map,将map中的value进行名称的拼接
                Map<String,String> map = JSON.parseObject(sku.getSpec(), Map.class);

                if (map != null && map.size() > 0) {
                    for (String value : map.values()) {
                        name += " "+value;
                    }
                }
                sku.setName(name);

                //设置spuid
                sku.setSpuId(spu.getId());
                //设置创建和修改时间
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());

                //商品分类id
                sku.setCategoryId(category.getId());
                //设置商品分类名称
                sku.setCategoryName(category.getName());
                //设置商品品牌
                sku.setBrandName(brand.getName());
                //将sku添加到数据库
                skuMapper.insertSelective(sku);
            }
        }
    }

    /**
     * 商品修改功能
     * @param goods
     */
    @Override
    @Transactional
    public void update(Goods goods) {
        Spu spu = goods.getSpu();
        List<Sku> skuList = goods.getSkuList();

        //修改spu
        spuMapper.updateByPrimaryKey(spu);

        //修改stuList
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("squId",spu.getId());
        //删除原先的skuList
        skuMapper.deleteByExample(example);

        //重新添加现有的skulist
        saveSkuList(goods);
    }


    /**
     * 删除商品,通过修改数据库表中删除字段的值来实现删除
     * @param id
     */
    @Override
    public void delete(String id) {
        //逻辑删除
        Spu spu = spuMapper.selectByPrimaryKey(id);

        if ("1".equals(spu.getIsMarketable())) {
            throw new RuntimeException("当前商品必须处于下架状态才能删除!");
        }

        //如果是下架状态,则修改商品状态,进行逻辑删除
        spu.setIsDelete("1");
        spu.setStatus("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    @Override
    public List<Spu> findList(Map<String,Object> searchMap) {
        Example example = createExample(searchMap);

        return spuMapper.selectByExample(example);
    }

    /**
     * 条件+分页  查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(Map<String,Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);

        Example example = createExample(searchMap);

        List<Spu> spuList = spuMapper.selectByExample(example);

        return (Page<Spu>) spuList;
    }

    @Override
    @Transactional
    public void audit(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("当前商品不存在!");
        }
        //判断当前spu是否处于删除状态
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("当前商品处于删除状态!");
        }

        //当存在商品且不处于删除状态,自动上架
        spu.setStatus("1");     //修改审核状态为1
        spu.setIsMarketable("1");   //修改上下架状态为1
        //执行修改操作
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    //商品下架功能
    @Override
    @Transactional
    public void pull(String id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);

        if (spu == null) {
            throw new RuntimeException("当前商品不存在!");
        }

        //判断当前商品是否处于删除状态
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("当前商品处于删除状态!");
        }

        //商品不处于删除状态,修改商品上架状态
        spu.setIsMarketable("0");   //修改商品为下架状态
        spuMapper.updateByPrimaryKey(spu);

    }

    /**
     * 商品上架功能
     * @param id
     */
    @Override
    @Transactional
    public void put(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);

        if (spu == null) {
            throw new RuntimeException("当前商品不存在!");
        }

        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("当前商品处于删除状态!");
        }

        if ("0".equals(spu.getStatus())) {
            throw new RuntimeException("当前商品尚未审核!");
        }

        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    @Override
    @Transactional
    public void restore(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断当前商品是否处于已删除状态
        if (!"1".equals(spu.getIsDelete())) {
            throw new RuntimeException("当前商品未删除!");
        }

        //修改相关的属性字段进行保存操作
        spu.setIsDelete("0");
        spu.setStatus("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    @Override
    @Transactional
    public void realDel(String id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);

        //判断当前商品是否处于已删除状态
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("该商品已删除!");
        }

        //执行删除操作
        spuMapper.deleteByPrimaryKey(id);

    }



    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andEqualTo("id",searchMap.get("id"));
            }
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andEqualTo("sn",searchMap.get("sn"));
            }
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
            }
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
            }
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
            }
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
            }
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
            }
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
            }
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
            }
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
            }
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andEqualTo("isMarketable",searchMap.get("isMarketable"));
            }
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andEqualTo("isDelete",searchMap.get("isDelete"));
            }
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andEqualTo("status",searchMap.get("status"));
            }

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }
}
